﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Analysis.DAL;
using Analysis.DAL.Repositories;
using Analysis.Entities;
using Analysis.Code;

namespace Analysis
{
    public partial class Setup : BaseDataPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!AccessConfirm("Настройка"))
            {
                throw new HttpException(401, "Доступ закрыт");
            }
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        public override void LoadData()
        {
            LoadDepart();
            LoadSaleChannel();
            LoadStorePoint();
        }

        public void LoadDepart()
        {
            using (var repo = RepositoryFactory.ResolveRepository<SetupRepository>())
            {
                IEnumerable<Depart> lstDepart = repo.FindDepart();
                
                string departName = lstDepart.Select(i => i.DepartName).ToList().Aggregate((current, next) => current + ";" + next) + ";";
                ScriptManager.RegisterStartupScript(upDepart, upDepart.GetType(), "departName", string.Format("departNameOld = '{0}';", departName), true);
                
                MaxOrderNumber = lstDepart.Max(i => i.OrderNumber);
                gridDepart.DataSource = lstDepart;
                gridDepart.DataBind();
                upDepart.Update();

                btnAddDepart.Visible = (MaxOrderNumber < 5);
            }
        }

        public void LoadSaleChannel()
        {
            using (var repo = RepositoryFactory.ResolveRepository<SetupRepository>())
            {
                IEnumerable<SaleChannel> lstSaleChannel = repo.FindSaleChannel();

                string saleChannel = "";
                if (lstSaleChannel.Count() > 0)
                    saleChannel = lstSaleChannel.Select(i => i.SaleChannelName).ToList().Aggregate((current, next) => current + ";" + next) + ";";
                ScriptManager.RegisterStartupScript(upSaleChannel, upSaleChannel.GetType(), "saleChannel", string.Format("saleChannelNameOld = '{0}';", saleChannel), true);

                gridSaleChannel.DataSource = lstSaleChannel;
                gridSaleChannel.DataBind();
                upSaleChannel.Update();
            }
        }

        public void LoadStorePoint()
        {
            using (var repo = RepositoryFactory.ResolveRepository<SetupRepository>())
            {
                IEnumerable<StorePoint> lstStorePoint = repo.FindStorePoint();
                
                string storePoint = "";
                if (lstStorePoint.Count() > 0)
                    storePoint = lstStorePoint.Select(i => i.StorePointName).ToList().Aggregate((current, next) => current + ";" + next) + ";";
                ScriptManager.RegisterStartupScript(upStorePoint, upStorePoint.GetType(), "storePoint", string.Format("storePointNameOld = '{0}';", storePoint), true);

                gridStorePoint.DataSource = lstStorePoint;
                gridStorePoint.DataBind();
                upStorePoint.Update();
            }
        }

        protected void gridDepart_RowDataBound(Object Sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Depart item = (Depart)e.Row.DataItem;

                ImageButton btn = (ImageButton)e.Row.FindControl("btnUp");
                btn.Visible = (!item.IsAdmin) && (item.OrderNumber > 1);
                btn = (ImageButton)e.Row.FindControl("btnDown");
                btn.Visible = (!item.IsAdmin) && (item.OrderNumber < MaxOrderNumber);

                btn = (ImageButton)e.Row.FindControl("btnDelete");
                btn.Visible = item.IsAdmin ? false : item.CanDelete;
            }
        }

        protected void gridDepart_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString());

            string result = SaveDepart();
            if (!string.IsNullOrEmpty(result))
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", string.Format("alert('{0}');", result), true);
                return;
            }

            switch (e.CommandName)
            {
                case "MoveUp":
                    using (var repo = RepositoryFactory.ResolveRepository<SetupRepository>())
                    {
                        repo.UpDepart(id);
                        LoadDepart();
                    }
                    break;
                case "MoveDown":
                    using (var repo = RepositoryFactory.ResolveRepository<SetupRepository>())
                    {
                        repo.DownDepart(id);
                        LoadDepart();
                    }
                    break;
                case "MakeDelete":
                    using (var repo = RepositoryFactory.ResolveRepository<SetupRepository>())
                    {
                        repo.DeleteDepart(id);
                        LoadDepart();
                    }
                    break;
            }
        }

        protected void btnSaveDepart_Click(object sender, EventArgs e)
        {
            string result = SaveDepart();
            if (!string.IsNullOrEmpty(result))
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", string.Format("alert('{0}');", result), true);
                return;
            }
            else
            {
                LoadDepart();
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('Сохранение успешно завершено!');", true);
            }
        }

        protected void btnAddDepart_Click(object sender, EventArgs e)
        {
            string result = SaveDepart();
            if (!string.IsNullOrEmpty(result))
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", string.Format("alert('{0}');", result), true);
                return;
            }

            using (var repo = RepositoryFactory.ResolveRepository<SetupRepository>())
            {
                repo.AddDepart();
                LoadDepart();
                //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('Должность добавлена успешно!');", true);
            }
        }

        protected string SaveDepart()
        {
            string result = "";

            string departId = "";
            string departName = "";

            foreach (GridViewRow item in gridDepart.Rows)
            {
                if (item.RowType != DataControlRowType.DataRow)
                    continue;

                departId += ((HiddenField)item.FindControl("hidDepartId")).Value + ";";
                departName += ((TextBox)item.FindControl("tbDepartName")).Text + ";";
            }

            using (var repo = RepositoryFactory.ResolveRepository<SetupRepository>())
            {
                result = repo.EditDepart(departId, departName);
            }

            return result;
        }

        protected void gridSaleChannel_RowDataBound(Object Sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                SaleChannel item = (SaleChannel)e.Row.DataItem;
                ImageButton btn = (ImageButton)e.Row.FindControl("btnDelete");
            }
        }

        protected void gridSaleChannel_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString());

            string result = SaveSaleChannel();
            if (!string.IsNullOrEmpty(result))
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", string.Format("alert('{0}');", result), true);
                return;
            }

            switch (e.CommandName)
            {
                case "MakeDelete":
                    using (var repo = RepositoryFactory.ResolveRepository<SetupRepository>())
                    {
                        repo.DeleteSaleChannel(id);
                        LoadSaleChannel();
                    }
                    break;
            }
        }

        protected void btnSaveSaleChannel_Click(object sender, EventArgs e)
        {
            string result = SaveSaleChannel();
            if (!string.IsNullOrEmpty(result))
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", string.Format("alert('{0}');", result), true);
                return;
            }
            else
            {
                LoadSaleChannel();
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('Сохранение успешно завершено!');", true);
            }
        }

        protected void btnAddSaleChannel_Click(object sender, EventArgs e)
        {
            string result = SaveSaleChannel();
            if (!string.IsNullOrEmpty(result))
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", string.Format("alert('{0}');", result), true);
                return;
            }

            using (var repo = RepositoryFactory.ResolveRepository<SetupRepository>())
            {
                repo.AddSaleChannel();
                LoadSaleChannel();
            }
        }

        protected string SaveSaleChannel()
        {
            string result = "";

            string SaleChannelId = "";
            string SaleChannelName = "";

            foreach (GridViewRow item in gridSaleChannel.Rows)
            {
                if (item.RowType != DataControlRowType.DataRow)
                    continue;

                SaleChannelId += ((HiddenField)item.FindControl("hidSaleChannelId")).Value + ";";
                SaleChannelName += ((TextBox)item.FindControl("tbSaleChannelName")).Text + ";";
            }

            using (var repo = RepositoryFactory.ResolveRepository<SetupRepository>())
            {
                result = repo.EditSaleChannel(SaleChannelId, SaleChannelName);
            }

            return result;
        }

        protected void gridStorePoint_RowDataBound(Object Sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                StorePoint item = (StorePoint)e.Row.DataItem;
                ImageButton btn = (ImageButton)e.Row.FindControl("btnDelete");
            }
        }

        protected void gridStorePoint_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString());

            string result = SaveStorePoint();
            if (!string.IsNullOrEmpty(result))
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", string.Format("alert('{0}');", result), true);
                return;
            }

            switch (e.CommandName)
            {
                case "MakeDelete":
                    using (var repo = RepositoryFactory.ResolveRepository<SetupRepository>())
                    {
                        repo.DeleteStorePoint(id);
                        LoadStorePoint();
                    }
                    break;
            }
        }

        protected void btnSaveStorePoint_Click(object sender, EventArgs e)
        {
            string result = SaveStorePoint();
            if (!string.IsNullOrEmpty(result))
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", string.Format("alert('{0}');", result), true);
                return;
            }
            else
            {
                LoadStorePoint();
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('Сохранение успешно завершено!');", true);
            }
        }

        protected void btnAddStorePoint_Click(object sender, EventArgs e)
        {
            string result = SaveStorePoint();
            if (!string.IsNullOrEmpty(result))
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", string.Format("alert('{0}');", result), true);
                return;
            }

            using (var repo = RepositoryFactory.ResolveRepository<SetupRepository>())
            {
                repo.AddStorePoint();
                LoadStorePoint();
            }
        }

        protected string SaveStorePoint()
        {
            string result = "";

            string StorePointId = "";
            string StorePointName = "";

            foreach (GridViewRow item in gridStorePoint.Rows)
            {
                if (item.RowType != DataControlRowType.DataRow)
                    continue;

                StorePointId += ((HiddenField)item.FindControl("hidStorePointId")).Value + ";";
                StorePointName += ((TextBox)item.FindControl("tbStorePointName")).Text + ";";
            }

            using (var repo = RepositoryFactory.ResolveRepository<SetupRepository>())
            {
                result = repo.EditStorePoint(StorePointId, StorePointName);
            }

            return result;
        }

        protected int MaxOrderNumber
        {
            get
            {
                if (this.ViewState["MaxOrderNumber"] == null)
                    return 0;
                return Convert.ToInt32(this.ViewState["MaxOrderNumber"].ToString());
            }
            set
            {
                this.ViewState["MaxOrderNumber"] = value.ToString();
            }
        }
    }
}